package com.hue.concurrent.day05;

/**
 * 循环输出a,b,c
 */
public class Demo05 {
    public static Flag flag = new Flag();

    public static void main(String[] args) {
        Print p1 = new Print(1);
        Print p2 = new Print(2);
        Print p3 = new Print(3);
        p1.start();
        p2.start();
        p3.start();
    }

    public static class Flag {
        public Integer flag = 1;
    }

    public static class Print extends Thread {
        public Integer num;

        public Print(Integer num) {
            this.num = num;
        }

        @Override
        public void run() {
            while (true){
                synchronized (flag) {
                    while (flag.flag != num) {
                        try {
                            flag.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(num);
                    flag.flag = (num + 1) > 3 ? 1 : num + 1;
                    flag.notifyAll();
                }
            }
        }
    }
}

